//
//  BKXComposeViewController.swift
//  微博
//
//  Created by 田凯 on 16/4/24.
//  Copyright © 2016年 田凯. All rights reserved.
//

import UIKit

class BKXComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
    
    //设置视图
    func setupUI(){
    setupNAV()
    view.backgroundColor = UIColor.whiteColor()
    //添加
    view.addSubview(composeView)
        
        
        // 通知 监听 键盘 frame 改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "KeyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        
    view.addSubview(composeToolBar)
    
        composeView.addSubview(pictureView)
        //设置约束
        composeView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        
        //底部toolbar
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.trailing.leading.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        //图片 view
        pictureView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width: ScreenW - 20, height: ScreenH - 20))
            make.leading.equalTo(10)
            make.top.equalTo(composeView).offset(100)
        }
        
    //监听 toolbar 的点击事件
        composeToolBar.buttonCloseBag = {[weak self](type: ComposeToolbarType) in
            
            switch type{
            case .picture:
                print("图片")
                self?.setImage()
            case .mention:
                print("2")
            case .trend:
                print("3")
            case .emoticon:
                print("4")
                self?.emotionKeyBoard()
            case .add:
                print("5")

            }
        
        }
        // 点击 加号 cell 跳转 方法
        pictureView.addIamgePicture = {[weak self] in
            
            self?.setImage()

        }
        
    }
    
    func KeyboardWillChangeFrame(noti: NSNotification){
//        print(noti)
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        print(rect)
        
        //更新 toolbar 的frame
        composeToolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - ScreenH)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            
            // MARK 不清楚
            self.view.layoutIfNeeded()
//            self.view.reloadInputViews()
        }
        
    }

    deinit{
    
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    //设置导航栏的视图
    func setupNAV(){
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "Cance")
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "提交", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
    navigationItem.titleView = titleView
    }
    
    // MARK: - 自定义titleview
    private lazy var titleView: UILabel = {
        
        let name = BKXUserAccountTools.sharedUserAccountTools.userAccount?.name ?? ""
        let titleStr = "发微博\n\(name)"
        //富文本
        let attr = NSMutableAttributedString(string: titleStr)
        //获取range
        let range = (titleStr as NSString).rangeOfString(name)
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
        
        
        
        let lab = UILabel(textcolor: ThemeColor, textFont: 15)
        
        lab.attributedText = attr
        lab.textAlignment = .Center
        lab.numberOfLines = 0
        //这句放在最后
        lab.sizeToFit()

        return lab
        
        }()
    // MARK: - 懒加载 textview
    private lazy var composeView : BKXComposeTextView = {
        let textView = BKXComposeTextView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.placeHoderStr = "怪你过分美丽 不开心的姑娘怪你过分美丽 不开心的姑娘怪你过分美丽 不开心的姑娘怪你过分美丽 不开心的姑娘怪你过分美丽 不开心的姑娘怪你过分美丽 不开心的姑娘"
        textView.delegate = self
        
        // MARK: - ?????
        textView.alwaysBounceVertical = true
        return textView
        
        }()
    // MARK: -  懒加载底部 toolbar
    private lazy var composeToolBar : BKXComposeToolbar = {
        let toolbar = BKXComposeToolbar()
        
        return toolbar
        
        
        }()
    
    // MARK: - 懒加载 图片collectionView
    private lazy var pictureView: BKXPictureCollectionView = {
        let picview = BKXPictureCollectionView()
        
//        picview.hidden = true
        return picview
        
        }()
    // MARK: - 懒加载自定义键盘
    private lazy var emotionKeyboard: BKXEmoticonKeyboardView = {
    let emotionKeyboard = BKXEmoticonKeyboardView()
       emotionKeyboard.frame = CGRect(x: 0, y: 0, width: ScreenW, height: 216)
    return emotionKeyboard
    }()
    
    
    // MARK: - 导航栏点击事件
    @objc func Cance(){
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc func send(){
        print("提交了")
    
    
    }
    
}

extension BKXComposeViewController : UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        // MARK: - ?????
        composeView.resignFirstResponder()
    }

}

// toolbar里的按钮点击事件
extension BKXComposeViewController{
    func setImage(){
    let  pickerVc = UIImagePickerController()
        
        pickerVc.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
        
        }else{
        print("不能打开张相机")
            presentViewController(pickerVc, animated: true, completion: nil)
        
        }
    
    }
    
    func emotionKeyBoard(){
        if composeView.inputView == nil{
        composeView.inputView = emotionKeyboard
        composeToolBar.isEmotion = true
        }else{
        composeView.inputView = nil
        composeToolBar.isEmotion = false
        }
        
        //刷新inputView
        composeView.reloadInputViews()
        //当点击按钮的时候 需要成为第一响应者
        composeView.becomeFirstResponder()
    
    }


}
// 代理方法
extension BKXComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        print(image)
//        composeView.backgroundColor = UIColor(patternImage: image)
        pictureView.addImage(getImageScale(image, imageW: 600))
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    // MARK: - 压缩图片的 方法
    func getImageScale(image: UIImage,imageW: CGFloat)->UIImage{
    
        if imageW > image.size.width{
        return image
        }
        let imageH = (imageW * image.size.height) / image.size.width
        // 开启图片上下文中
        UIGraphicsBeginImageContext(CGSize(width: imageW, height: imageH))
        // 渲染
        image.drawInRect(CGRect(x: 0, y: 0, width: imageW, height: imageH))
        let  reslt = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        return reslt
        
    }

}

